package com.roc.web.action.terminal;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.roc.common.Excel2007TermFileProcessor;
import com.roc.common.FileProcessor;
import com.roc.page.BaseAction;
import com.roc.pojo.Operators;
import com.roc.pojo.OrgBean;
import com.roc.pojo.YjPosInfo;
import com.roc.service.ITerminalService;
import com.roc.service.IorgService;
import com.roc.util.Utils;
import com.roc.util.constant.ConfigProperties;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;
@Controller
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
@Namespace("/termBatchAllotRecall")
public class TermianlBatchAllotRecallAction extends BaseAction{
private Logger logger=LogManager.getLogger(TerminalSnLeadingAction.class);
    private Operators merchant;
	private List<OrgBean> orgList=new ArrayList<OrgBean>();
	private File upload;
	private YjPosInfo posInfo;
	
	private String msg;
	
	@Autowired
	IorgService orgService;
	
	@Autowired
	ITerminalService terminalService;
	
	@Action(value = "termBatchAllotRecallInfoJsp",
			results = { @Result(location = "/pages/terminal/batchTermSnAllotRecall.jsp") })
	public String termBatchAllotRecallInfoAction() throws Exception {
		org();
		return SUCCESS;
	}
	
	@Action(value = "batchTermSNAllotRecall", interceptorRefs = {
			@InterceptorRef(value = "token"),
			@InterceptorRef(value = "rocDefaultStack", params = {
					"fileUpload.allowedExtensions", "xlsx",
					"fileUpload.maximumSize", "100000000" }) }, results = { 
			@Result(location = "/message.jsp"),
			@Result(name = "error", location = "/error.jsp"),
			@Result(name = "invalid.token", location = "/error.jsp")
	    })
	public String batchTermSNAllotRecall() throws Exception{
		org();
	    merchant = (Operators) ActionContext.getContext().getSession().get(Constant.SESSION_LOGIN_MERCHANT);
	    List<Long> idList = null;
        List<String> serialNumArray = null;
		if(upload == null){
			msg="请选择文件";
			return SUCCESS;
		}
		try {
			String msg = "";
		    StringBuffer errorMsg = new StringBuffer();
			int index = 0;
			int successInx = 0;
			int failInx = 0;
			List<YjPosInfo> deleteRepeatList = null;
			FileProcessor processor = new Excel2007TermFileProcessor();
			List<YjPosInfo> terms = (List<YjPosInfo>) processor.process(upload);
			String context = "";//提示信息
	    	if((merchant.getRoleType().trim().equals("00")||merchant.getRoleType().trim().equals("01"))){//管理员和系统管理员
	    	}else{
		    	idList = terminalService.getOpertorsIdsTreeById(merchant.getId());
	    	}
			List<String> failList = new ArrayList<String>();
			deleteRepeatList = getDeleteRepeatAgent(terms);
            if(deleteRepeatList.size()==0){
            	errorMsg.append("你好，你的Execl文件中不存在数据记录!");
				addActionError(errorMsg.toString());
            }
            else{
            	if(deleteRepeatList.size()>1000){
					errorMsg.append("你好，你的Execl文件中在数据记录数超过1000条,请分批进行撤回！");
					addActionError(errorMsg.toString());
				}
            	else{            		
            		for(YjPosInfo pos:deleteRepeatList){
            			if((merchant.getRoleType().trim().equals("00")||merchant.getRoleType().trim().equals("01"))){//管理员和系统管理员
                  		  serialNumArray = (List<String>)terminalService.getPosInfosForBatchRecall(Utils.changeCharUpperCase(pos.getSerialNum()), posInfo.getOrgCode(),null, posInfo.getPosBrand(), posInfo.getPosType(), posInfo.getPosName(), merchant);
            	    	}else{
               			  serialNumArray = (List<String>)terminalService.getPosInfosForBatchRecall(Utils.changeCharUpperCase(pos.getSerialNum()), posInfo.getOrgCode(), merchant.getId(), posInfo.getPosBrand(), posInfo.getPosType(), posInfo.getPosName(), merchant);
            	    	}
            			 if(serialNumArray!=null && serialNumArray.size()>0){
            				//terminalService.terminalAllotRecallBySN(Utils.changeCharUpperCase(pos.getSerialNum()), merchant, idList);
          			  	    successInx++;
            			 }
            			 else{
            				failInx++;
          					errorMsg.append(pos.getSerialNum()).append(",").append("\n");
            			 }
                     	context = "操作员【" + merchant.getAccountNo() + "】成功撤回【"+ successInx+ "】个终端序列号";
            		}
            		
                    if(errorMsg.length()>0){
                    	index = errorMsg.toString().lastIndexOf(",");
        				msg = errorMsg.toString().substring(0, index);
        				if(msg.length()>0){
                        	context = "操作员【" + merchant.getAccountNo() + "】成功撤回【"+ successInx+ "】个终端序列号,有"+failInx+"个撤回失败,失败的终端序列号:"+msg;
        				}
    				}
    				addActionError(context);
            	}
            }
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			addActionError(e.getMessage());
		}
		return SUCCESS;
	}
	/**
     * 去除重复终端序列号数据
     * @param list
     * @return
     */
	private List<YjPosInfo> getDeleteRepeatAgent(List<YjPosInfo> list){
		List<YjPosInfo>  newList = new ArrayList<YjPosInfo>();
		Map<String,YjPosInfo> map = new HashMap<String,YjPosInfo>();
		for(YjPosInfo agent:list){
			if(agent.getSerialNum()!=null && !"".equals(agent.getSerialNum())){
				if(map.get(agent.getSerialNum())==null){
				  map.put(agent.getSerialNum(), agent);
				}
			}	
		}
		for(String key : map.keySet()) {
			newList.add(map.get(key));
		}
		return newList;
	}
	private void org(){
		try{
			Operators logingOperators=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
			orgList=orgService.listOrgs(logingOperators);
			getRequest().setAttribute("orgList", orgList);
			Map<String,String> brandMap=ConfigProperties.getPOSBrand();
			Map<String,String> nameMap=ConfigProperties.getPOSName();
			Map<String,String> typeMap=ConfigProperties.getPOSType();
			getRequest().setAttribute("brandMap", brandMap);
			getRequest().setAttribute("nameMap", nameMap);
			getRequest().setAttribute("typeMap", typeMap);
			//加载角色类型 
			Map roleMap=new HashMap();
			if(logingOperators.getRoleType().equals(Role.AGENT.getCode())){
				roleMap.put(Role.AGENT.getCode(),Role.AGENT.getName());
			}else{
				roleMap.put(Role.O_MANAGER.getCode(),Role.O_MANAGER.getName());
				roleMap.put(Role.AGENT.getCode(),Role.AGENT.getName());
			}
			getRequest().setAttribute("roleMap",roleMap);
		}catch (Exception e) {
			// TODO: handle exception
		}
	}
	public File getUpload() {
		return upload;
	}
	public void setUpload(File upload) {
		this.upload = upload;
	}
	public YjPosInfo getPosInfo() {
		return posInfo;
	}
	public void setPosInfo(YjPosInfo posInfo) {
		this.posInfo = posInfo;
	}
	public String getMsg() {
		return msg;
	}
	public void setMsg(String msg) {
		this.msg = msg;
	}

	public List<OrgBean> getOrgList() {
		return orgList;
	}

	public void setOrgList(List<OrgBean> orgList) {
		this.orgList = orgList;
	}
	
}
